package collect

import (
	"fmt"
	"strings"
	"time"

	"gitee.com/xuesongtao/gotool/base"
	pslog "gitee.com/xuesongtao/ps-log"
	"gitee.com/xuesongtao/ps-log/line"
	"github.com/gogf/gf/os/glog"
)

func (c *CollectProject) GetPsHandle() (*pslog.Handler, error) {
	// 过期在 第二天的 00:10:00
	// tomorrow := base.Datetime2TimeObj(time.Now().AddDate(0, 0, 1).Format(base.DateFmt) + base.StartTimeSuffix).Add(10 * time.Minute)
	obj := &pslog.Handler{
		LoopParse:   c.Loop,
		CleanOffset: false,
		Tail:        c.Tail,
		Change:      50,
		ExpireDur:   time.Hour,
		// ExpireAt:    time.Time{},
		// MergeRule: nil,
		Targets: make([]*pslog.Target, 0, len(c.Collect)),
		Ext:     genPsLogExt(c.Name, ""),
		// NeedCollect: nil,
	}
	if c.WatchType == "dir" {
		obj.NeedCollect = func(filename string) bool {
			return strings.HasSuffix(filename, c.LogRule.GetLogName())
		}
	}

	if c.ParseStack {
		mul := line.NewMulti()
		if err := mul.StartPattern(c.StartLinePattern); err != nil {
			return nil, fmt.Errorf("mul.StartPattern is failed, err: %v", err)
		}
		obj.MergeRule = mul
	}

	for _, collect := range c.Collect {
		if collect.Ignore {
			glog.Warningf("%q collect %s set ignore, it will skip collect", c.CfgFilename, base.Str(collect.Target))
			continue
		}
		for _, target := range collect.Target {
			if target.Content == "" {
				continue
			}

			tmp := &pslog.Target{
				Content:  target.Content,
				Excludes: target.Exclude,
				To:       make([]pslog.PsLogWriter, 0, 5),
				Ext:      genPsLogExt(c.Name, collect.Title),
			}
			for _, cfg := range collect.TosCfg {
				wt, err := cfg.GetWriteTo()
				if err != nil {
					glog.Error("cfg.GetWriteTo is failed, err:", err)
					continue
				}
				tmp.To = append(tmp.To, wt)
			}
			obj.Targets = append(obj.Targets, tmp)
		}
	}
	return obj, nil
}
